<template>
	<view style="width: 100%;display: flex;flex-wrap: wrap;padding: 15rpx;background: #666;">
		<video src="" id="aaaa"></video>
		<view v-for="(item,k) in dataList" style="width: 350rpx;height: calc(50vh - 100px);background: 999;display: flex;flex-direction: column;">
			<video controls muted autoplay :id="`vd_${item.id}`"></video>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				id: '',
				roomId: '',
				name: '',
				mtname: '',
				dataList: [],
				myvddata: {},
				cameraType: "user",
				cameraChangeLoading: false,
			}
		},
		onLoad({
			id,
			roomId,
			name,
			mtname
		}) {
			this.id = id
			this.roomId = roomId
			this.name = name
			this.mtname = mtname
			uni.setNavigationBarTitle({
				title: mtname
			})
			this.publishStream({
				video:true,
				audio:true
			})
		},
		methods: {
			subStream: async function({
				id,
				name,
				roomId,
				audio,
				video,
				avatar
			}) {
				const pc = new RTCPeerConnection(null);
				pc.addTransceiver('audio', {
					direction: 'recvonly'
				});
				pc.addTransceiver('video', {
					direction: 'recvonly'
				});
				let offer = await pc.createOffer();
				let stream = new MediaStream();
				pc.ontrack = function(event) {
					console.log(event);
					stream.addTrack(event.track);
				};
				await pc.setLocalDescription(offer);
				let session = await new Promise(function(resolve, reject) {
					let data = {
						api: `https://dx11.haoleen.com/rtc/v1/play/`,
						tid: id,
						streamurl: `webrtc://dx11.haoleen.com/${roomId}/${id}`,
						clientip: null,
						sdp: offer.sdp,
					};
					console.log('Generated offer: ', data);

					const xhr = new XMLHttpRequest();
					xhr.onload = function() {
						if (xhr.readyState !== xhr.DONE) return;
						if (xhr.status !== 200) return reject(xhr);
						const data = JSON.parse(xhr.responseText);
						console.log('Got answer: ', data);
						return data.code ? reject(xhr) : resolve(data);
					};
					xhr.open('POST', `https://dx11.haoleen.com/rtc/v1/play/`, true);
					xhr.setRequestHeader('Content-type', 'application/json');
					xhr.send(JSON.stringify(data));
				});
				await pc.setRemoteDescription(
					new RTCSessionDescription({
						type: 'answer',
						sdp: session.sdp
					}),
				);

				function close() {
					stream.getTracks().forEach(function(track) {
						track.stop();
						stream.removeTrack(track);
					});
					// stream.close()
					pc.close();
					document.getElementById("vd_" + id).srcObject = null
				}

				const vdata = {
					id,
					roomId,
					pc,
					stream,
					name,
					avatar,
					audio: audio ?? false,
					video: video ?? false,
					close,
				};

				this.dataList.push(vdata)
				setTimeout(() => {
					document.getElementById("vd_" + id).srcObject = stream
				}, 1500)
			},
			publishStream: async function(options) {
				const id = this.id
				const roomId = this.roomId
				const name = this.name
				const pc = new RTCPeerConnection(null);
				pc.addTransceiver('audio', {
					direction: 'sendonly'
				});
				pc.addTransceiver('video', {
					direction: 'sendonly'
				});
				const stream = await navigator.mediaDevices.getUserMedia({
					audio: true,
					video: {
						facingMode: options.videoType ?? "environment"
					},
				});
				document.getElementById("aaaa").srcObject = stream
				this.cameraType = options.videoType ?? "environment"
				console.log(stream);
				stream.getTracks().forEach(function(track) {
					pc.addTrack(track);
					if (track.kind === 'audio') {
						if (options.audio === false) {
							track.enabled = false;
						}
					}
					if (track.kind === 'video') {
						if (options.video === false) {
							track.enabled = false;
						}
					}
				});
				let offer = await pc.createOffer();
				await pc.setLocalDescription(offer);
				let session = await new Promise(function(resolve, reject) {
					let data = {
						api: `https://dx11.haoleen.com/rtc/v1/publish/`,
						tid: id,
						streamurl: `webrtc://dx11.haoleen.com/${roomId}/${id}`,
						clientip: null,
						sdp: offer.sdp,
					};
					console.log('Generated offer: ', data);

					const xhr = new XMLHttpRequest();
					xhr.onload = function() {
						if (xhr.readyState !== xhr.DONE) return;
						if (xhr.status !== 200) return reject(xhr);
						const data = JSON.parse(xhr.responseText);
						console.log('Got answer: ', data);
						if (data.code === 400) {
							resolve(false);
						}
						return data.code ? reject(xhr) : resolve(data);
					};
					xhr.open('POST', `https://dx11.haoleen.com/rtc/v1/publish/`, true);
					xhr.setRequestHeader('Content-type', 'application/json');
					xhr.send(JSON.stringify(data));
				});
				console.log(session);
				if (session === false) {
					return false;
				}
				await pc.setRemoteDescription(
					new RTCSessionDescription({
						type: 'answer',
						sdp: session.sdp
					}),
				);

				function muteAudio(type) {
					stream.getTracks().forEach(function(track) {
						if (track.kind === 'audio') {
							track.enabled = type ?? false;
						}
					});
				}

				function muteVideo(type) {
					stream.getTracks().forEach(function(track) {
						if (track.kind === 'video') {
							track.enabled = type ?? false;
						}
					});
				}
				const _this = this
				async function unpublish() {
					try {
						stream.getTracks().forEach(function(track) {
							track.stop();
							stream.removeTrack(track);
						});
						// stream.close()
						pc.close();
						document.getElementById("vd_" + id).srcObject = null
					} catch (e) {
						//TODO handle the exception
					}
					// _this.dataList = _this.dataList.filter(e => e.id != _this.id)
					// const cid = await getPublishCidById(options.roomId, options.id);
					// console.log(cid);
					// const ret = await axios.delete(
					//   `${process.env.srsUrl}/api/v1/clients/${cid}`,
					// );
				}

				const vdata = {
					id: id,
					name: name,
					roomId: roomId,
					pc,
					stream,
					audio: options.audio == false ? false : true,
					video: options.video == false ? false : true,
					user: {
						id,
						name
					},
					muteAudio,
					muteVideo,
					unpublish: unpublish,
				};
				this.dataList.push(vdata)
				this.myvddata = vdata
				setTimeout(() => {
					document.getElementById("vd_" + id).srcObject = stream
				}, 2000)
			}

		}
	}
</script>

<style>
</style>